package com.bookseek.xreader;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.bookseek.xreader.views.fragments.GujiFragment;
import com.bookseek.xreader.views.fragments.MyFragment;
import com.bookseek.xreader.views.fragments.PoemFragment;
import com.bookseek.xreader.views.fragments.WenFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationBarView;


public class MainActivity extends AppCompatActivity  {

    private WebView webViewEle;
    private PoemFragment poemFragment;
    private GujiFragment gujiFragment;
    private WenFragment wenFragment;
    private MyFragment myFragment;
    private BottomNavigationView bottomNavigationView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bottomNavigationView = findViewById(R.id.bottomNav);
        bottomNavigationView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener(){
           @Override
           public boolean onNavigationItemSelected(@NonNull MenuItem item) {
               int itemId = item.getItemId();
               showFragment(itemId);
               return true;
           }
       });
        if(savedInstanceState == null){
            //设置默认值
            bottomNavigationView.setSelectedItemId(R.id.gujiNav);
        }

    }

    public void bkCode(){
        webViewEle.getSettings().setJavaScriptEnabled(true);
        webViewEle.getSettings().setDomStorageEnabled(true);
        webViewEle.getSettings().setAllowFileAccess(true);
        webViewEle.getSettings().setAllowContentAccess(true);
        webViewEle.setWebChromeClient(new WebChromeClient());
        webViewEle.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                request.setMimeType(mimeType);
                String cookies = CookieManager.getInstance().getCookie(url);
                request.addRequestHeader("cookie", cookies);
                request.addRequestHeader("User-Agent", userAgent);
                request.setDescription("Downloading PDF file");
                request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimeType));

                DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                downloadManager.enqueue(request);
            }
        });
        webViewEle.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });
    }
    public void myclick(View view) {
       Log.i("dx","ddd");
       webViewEle.loadUrl("https://url14.ctfile.com/f/63388114-1489878580-78abe3?p=8043");
    }


    private void showFragment(int itemId){
        Log.i("showFragment==>",itemId+"");
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        hideFragment(transaction);
        //典籍库
        if(itemId == R.id.wenNav){
            if(wenFragment == null){
                wenFragment =  new WenFragment();
                Log.i("DXM","Add--->wenFragment"+wenFragment);
                transaction.add(R.id.mainContent,wenFragment,"wen");
            }else{
                transaction.show(wenFragment);
            }
        }
        //诗词库
        if(itemId == R.id.poemNav){
            if(poemFragment == null){
                poemFragment = new PoemFragment();
                transaction.add(R.id.mainContent,poemFragment,"poem");
            }else{
                transaction.show(poemFragment);
            }
        }
        //我的
        if(itemId == R.id.myNav){
            if(myFragment == null){
                myFragment = new MyFragment();
                transaction.add(R.id.mainContent,myFragment,"my");
            }else{
                transaction.show(myFragment);
            }
        }
        //古籍
        if(itemId == R.id.gujiNav){
            if(gujiFragment == null){
                gujiFragment = new GujiFragment();
                transaction.add(R.id.mainContent,gujiFragment,"guji");
            }else{
                transaction.show(gujiFragment);
            }
        }
        transaction.commit();
    }

    public PoemFragment getPoemFragment() {
        if(poemFragment != null){
            return poemFragment;
        }
        Fragment fragment = getSupportFragmentManager().findFragmentByTag("poem");
        if(fragment != null){
            poemFragment = (PoemFragment) fragment;
        }
        return poemFragment;
    }

    public GujiFragment getGujiFragment() {
        if(gujiFragment != null){
            return gujiFragment;
        }
        Fragment fragment = getSupportFragmentManager().findFragmentByTag("guji");
        if(fragment != null){
            gujiFragment = (GujiFragment) fragment;
        }
        return gujiFragment;
    }

    public WenFragment getWenFragment() {
        if(wenFragment != null){
            return wenFragment;
        }
        Fragment fragment = getSupportFragmentManager().findFragmentByTag("wen");
        if(fragment != null){
            wenFragment = (WenFragment) fragment;
            Log.i("DXM","wenFragment 游离状态===> 重新关联引用"+wenFragment);
        }
        return wenFragment;
    }

    public MyFragment getMyFragment() {
        if(myFragment != null){
            return myFragment;
        }
        Fragment fragment = getSupportFragmentManager().findFragmentByTag("my");
        if(fragment != null){
            myFragment = (MyFragment) fragment;
        }
        return myFragment;
    }

    private void hideFragment(FragmentTransaction transaction){
        boolean gujiNotNull = getGujiFragment() != null;
        if(gujiNotNull){
            transaction.hide(gujiFragment);
        }
        boolean wenNotNull = getWenFragment() != null;
        if(wenNotNull){
            transaction.hide(wenFragment);
        }
        boolean poemNotNull = getPoemFragment() != null;
        if(poemNotNull){
            transaction.hide(poemFragment);
        }
        boolean myNotNull = getMyFragment() != null;
        if(myNotNull){
            transaction.hide(myFragment);
        }
        Log.i("DXM",String.format("gujiNotNull=%s,wenNotNull=%s,poemNotNull=%s,myNotNull=%s",gujiNotNull,wenNotNull,poemNotNull,myNotNull));
    }
}